// 顶升前检查
<template>
    <f7-page class="common-page page-tab has-bottom-btns">
      <f7-navbar>
          <f7-nav-left>
              <f7-link back icon-material="chevron_left" force></f7-link>
          </f7-nav-left>
          <f7-nav-title>顶升前检查</f7-nav-title>
          <f7-nav-right></f7-nav-right>
      </f7-navbar>
      <div class="common-page-content">
        <van-tabs :lazy-render="false" sticky>
          <van-tab name="#tab1" title="设备检查" id="#tab1">
            <!-- 设备检查 -->
            <div id="tab1" class="p15">
              <v-check-list-all
                v-if="controlData.property.equipmentType"
                :dataKey="$f7route.query.caseId||models.model.caseId"
                typeCode="EQM_UP_PREPARE_QZJX"
                uploadId="list1"
                ref="list1"
                :galleryOptions="{ multiple: true}" 
                @success="(val)=>list$1=val"
                :showPass="taskCode!='usertask2'&&taskCode!='usertask1'||(taskCode=='usertask3'&&pageAction!='view')"
                :disabledPass="!canCheck"
                :disabled="!canEdit"
                :attachCraneType="controlData.property.equipmentType"
                :address="address"
              />
            </div>
          </van-tab>
          <van-tab name="#tab2" title="安装条件" id="#tab2">
            <!-- 安装条件 -->
            <div id="tab2" class="p15">
              <v-check-list-all
                v-if="controlData.property.equipmentType"
                :dataKey="$f7route.query.caseId||models.model.caseId"
                typeCode="EQM_UP_PREPARE_AZTJ"
                uploadId="list2"
                ref="list2"
                :galleryOptions="{ multiple: true}" 
                @success="(val)=>{list$2=val;updateNum++;}"
                :showPass="taskCode!='usertask2'&&taskCode!='usertask1'||(taskCode=='usertask3'&&pageAction!='view')"
                :disabledPass="!canCheck"
                :showEmpty="false"
                :disabled="!canEdit"
                :attachCraneType="controlData.property.equipmentType"
                :address="address"
              />
              <van-form ref="form" :readonly="!canEdit" class="myForm" v-if="updateNum>0">
                <div class="qzjx-card df-box">
                  <div class="index">{{list$2.length+1}}</div>
                  <div class="right-content-box">
                    <div class="title">检查结论</div>
                    <van-field name="radio" :rules="[{ required: true, message: '请选择' }]" class="my-radio">
                      <template #input>
                        <van-radio-group v-model="models.process.isRequire" :disabled="!canEdit">
                          <van-radio :name="1">条件满足</van-radio>
                          <van-radio :name="0">条件不满足</van-radio>
                        </van-radio-group>
                      </template>
                    </van-field>
                  </div>
                </div>
                <div class="qzjx-card df-box">
                  <div class="index">{{list$2.length+2}}</div>
                  <div class="right-content-box">
                    <div class="title">检查日期</div>
                    <van-field
                      readonly
                      clickable
                      name="calendar"
                      v-model="models.process.checkTime"
                      placeholder="点击选择日期"
                      right-icon="arrow"
                      :rules="[{ required: true, message: '请选择' }]"
                      @click="canEdit?showCalendar = true:''"
                    />

                    <van-calendar v-model="showCalendar" :min-date="new Date(2018, 0, 1)" @confirm="onConfirm" color="#1990FF"/>
                  </div>
                </div>
                <div class="qzjx-card df-box">
                  <div class="index">{{list$2.length+3}}</div>
                  <div class="right-content-box">
                    <div class="title">检查意见</div>
                    <van-field
                      v-model="models.model.memo"
                      rows="5"
                      autosize
                      type="textarea"
                      placeholder="请输入检查意见"
                      :rules="[{ required: true, message: '请填写' }]"
                    />
                  </div>
                </div>
              </van-form>
            </div>
          </van-tab>
          <van-tab name="#tab3" title="作业人员" id="#tab3">
            <!-- 作业人员 -->
            <div id="tab3">
              <!-- <van-notice-bar color="#FD5050" background="#FFF3F3" left-icon="info-o" wrapable :scrollable="false">
                人员说明：塔吊：5个安拆工、1个安全员、1个司机、1个信号工共8人。升降机：4个安拆工、1个安全员、1个司机共6人。技术负责人作业前不用人脸识别，如有监督站要求到场，请在现场顶升环节拍照即可 。
              </van-notice-bar> -->
              <v-person-check
                :list="controlData.directorPersonList"
                @check="(val,item)=>checkPerson(val,'directorPersonList',item)"
                title="安装单位技术负责人、专职安全员"
                listName="directorPersonList"
                :disabled="supCanCheck"
                :canUpdatePerson="canUpdatePerson"
              />
              <v-person-check
                :list="controlData.driverPersonList"
                @check="(val,item)=>checkPerson(val,'driverPersonList',item)"
                title="司索、司机"
                listName="driverPersonList"
                :disabled="supCanCheck"
                :canUpdatePerson="canUpdatePerson"
              />
              <v-person-check
                :list="controlData.installPersonList"
                @check="(val,item)=>checkPerson(val,'installPersonList',item)"
                title="安拆作业人员"
                listName="installPersonList"
                :disabled="supCanCheck"
                :canUpdatePerson="canUpdatePerson"
              />
            </div>
          </van-tab>
          <van-tab name="#tab4" title="流程进度" id="#tab4">
            <!-- 流程进度 -->
            <div id="tab5" class="p15">
              <section class="qzjx-card">
                <div class="title" style="font-size:16px;">业务流程</div>
                <v-workflow-step :data="history"></v-workflow-step>
              </section>
              <section class="qzjx-card">
                <div class="title" style="font-size:16px;">操作记录</div>
                <v-workflow-list v-if="controlData.workflow" :data="controlData.workflow.history||[]"></v-workflow-list>
              </section>
            </div>
          </van-tab>
        </van-tabs>
        <!-- 审核意见 -->
        <v-popup-opinion
            v-model="showPinion"
            :selectUser="selectUser"
            ref="opinion"
            @save="saveDetects('showPinion')"
        >
        </v-popup-opinion>
        <!-- 审核意见 end -->
        <v-popup-opinion
            v-model="showPinion1"
            :selectUser="selectUser"
            ref="opinion"
            @save="saveDetects('showPinion1')"
        >
        </v-popup-opinion>
      </div>
      <!-- v-has="'risk:riskList:save'" -->
      <f7-toolbar position="bottom" no-shadow class="fff" v-if="canEdit||canCheck">
        <!-- 顶升单位填写 -->
        <template v-if="canEdit">
          <f7-button fill class="submit-btn plain-btn" @click="saveDraft()">保存草稿</f7-button>
          <f7-button fill class="submit-btn" @click="fnSubmit()">提交</f7-button>
        </template>
        <!-- 施工审核/监理审核 -->
        <template v-if="canCheck">
          <f7-button fill class="submit-btn plain-btn" @click="fnCheck('showPinion')">退回</f7-button>
          <f7-button fill class="submit-btn" @click="fnCheck('showPinion1')">通过</f7-button>
        </template>
      </f7-toolbar>
    </f7-page>
</template>

<script>
import controller from "@/libs/framework/workflowController"
import mixin from "../js/mixin";
export default class instance extends controller {
    onBeforeInit () {
        this.urls = {
            model: ["/workflow/serviceGuideExt/getEntityByCode","/equipment/eqmUpPrepare/workflow/getWorkflowViewModel"],
        };
    }

    onInit () {
      this.$params.appCode = "eqmUpPrepare";
    }
    onBeforeQuery (type, conditions, params) {}
    onAfterQuery (type, isSuccess, result) {
      if(type=='form'){
        if(result.controlData.progress){
          this.context.history=result.controlData.progress.data
          this.context.taskCode=result.controlData.progress.taskCode
        }else{
          this.context.history=[]
        }
      }else if(type=='form$1'){
        if(!result.models.process.checkTime) {
          result.models.process.checkTime = this.vm.$formatter.formatDate(new Date(), 'yyyy-MM-dd')
        }else{
          result.models.process.checkTime = this.vm.$formatter.formatDate(result.models.process.checkTime, 'yyyy-MM-dd')
        }
        // if(result.pageAction=='create') {
        //   this.context.urls.processSave=`${result.urls.processSave}?appCode=${this.$params.appCode}&pageAction=${result.pageAction}&version=1`
        //   this.vm.super.save(result.models,false,'',false)
        // }
      }
      return result;
    }
    onAfterSave (isSuccess, result) {
        if (isSuccess) {
            this.context.models.model=result.parameters.models.model
        }
    }
    mixin () {
        return {
            components: {},
            mixins: [mixin],
            data () {
                return {
                  urls:{
                    processSave:''
                  },
                  checkPass:1,
                  updateNum:0,
                  showPinion:false,
                  showPinion1:false,
                    taskCode:'',
                    showCalendar:false,
                    models: {
                      equipmentDetects:[],
                      installConditionDetects:[],
                      process:{
                        checkTime:'',
                        isRequire:true,
                      },
                      model:{
                        memo:''
                      }
                    },
                    controlData:{
                      property:{},
                      workflow:{},
                      engineeBaseInfo:{},
                      maintenanceOrg:{},
                      installOrg:{},
                      isInsOrg:true,
                    },
                    history:[],
                    selectUser: {
                        selectComment: null,
                        comment: null,
                        comments: [],
                        tran: [],
                        activity: "",
                        users: [],
                    },
                    pageAction:'',
                    address:'',
                };
            },
            mounted () {},
            computed: {
              // 是否安装单位
              isInsOrg(){
                return this.controlData.isInsOrg
              },
              // 审核单位编辑
              canCheck(){
                if(this.pageAction=='edit'&&(this.taskCode=='usertask3'||this.taskCode=='usertask4')&&this.models.model.pstatus!=999){
                  return true
                }
                return false
              },
              // 安装单位编辑
              canEdit(){
                if(this.taskCode=='usertask2'&&(this.pageAction=='edit'||this.pageAction=='create')&&this.models.model.pstatus!=999){
                  return true
                }
                return false
              },
            },
            created () {
              this.loadLocation()
            },
            methods: {
              //获取地址
              loadLocation() {
                  let self = this
                  self.$util.getCurrentPosition(
                      (pos) => {
                          if (pos.addresses) {
                              self.address = pos.addresses
                          }else if(pos.data) {
                              self.address = pos.data.name
                          }
                      },
                      (error) => {
                          // self.$f7.dialog.toast(
                          //     '获取定位失败,请确认是否授权定位功能'
                          // )
                      }
                  )
              },
              saveDetects(type){
                // this.pageAction='edit'
                let arr=[...this.list$1,...this.list$2]
                let detects=arr.map(item=>{
                  return {
                    caseId:this.models.model.caseId,
                    dicId:item.id,
                    isPass:item.isPass,
                    isNil:item.isNil,
                  }
                })
                this.$util
                .getPromise("/equipment/eqmCase/saveDetects", {
                  detects,
                })
                .then((r) => {
                  this[type]=false
                  if(r&&r.success){
                    if(type=='showPinion1'){
                      this.send();
                    }else{
                      this.saveBack()
                    }
                  }else{
                    this.$f7.dialog.alert(r.message || '提交失败');
                  }
                }).catch(err=>{
                  console.log(err);
                });
              },
              saveDraft(){
                // this.pageAction='edit'
                // this.save(this.models)
                this.super.save(this.models,false,'',true,'保存成功')
              },
              beforeCheck(){
                let num=0;
                this.list$1.forEach(item=>{
                  if(item.isPass==null){
                    num++
                  }
                })
                this.list$2.forEach(item=>{
                  if(item.isPass==null){
                    num++
                  }
                })
                if(num>0){
                  return false
                }else{
                  return true
                }
              },
              fnCheck(show){
                if(this.taskCode=='usertask4'){
                  this[show]=true
                  // let flag = this.controlData.directorPersonList.every((currentValue)=> {
                  //     return currentValue.authTime
                  // })
                  // let flag1 = this.controlData.driverPersonList.every((currentValue)=> {
                  //     return currentValue.authTime
                  // })
                  // let flag2 = this.controlData.installPersonList.every((currentValue)=> {
                  //     return currentValue.authTime
                  // })
                  // let arr=[]
                  // if ((flag&&flag1&&flag2)||show == 'showPinion') {
                  //     this[show]=true
                  // }else{ // 点击通过时才校验
                  //   if(!flag) arr.push('安装单位技术负责人、专职安全员')
                  //   if(!flag1) arr.push('司索、司机')
                  //   if(!flag2) arr.push('安拆作业人员')
                  //   this.$toast(`${arr.toString()}的作业人员未全部核对！`)
                  // }
                }else{
                  if(this.beforeCheck()){
                    this[show]=true
                  }else{
                    this.$toast('请选择意见项！')
                  }
                }
              },
              saveBack(){
                this.super.fnBackJump(
                  this.selectUser.comment,
                  (result) => {
                    this.$f7.preloader.hide();
                    if (result.success) {
                      this.showPinion=false
                      this.refreshData('退回成功')
                    }else{
                      this.$f7.dialog.alert(result.message)
                    }
                  },
                  (e)=>{
                    console.log('退回失败---',e);
                    this.$f7.preloader.hide();
                  }
                )
              },
              refreshData(msg) {
                this.$f7.dialog.alert(msg, () => {
                  this.$f7.popup.close();
                  this.$f7.views.current.router.back({force:true})
                })
              },
              checkPerson(index,name,item){
                console.log(item);
                this.controlData[name][index].authTime = 1
              },
              onConfirm(date) {
                this.models.process.checkTime = this.$formatter.formatDate(date, 'yyyy-MM-dd');
                this.showCalendar = false;
              },
              fnSubmit(){
                this.$refs.form
                        .validate()
                        .then(async (_) => {
                          let flag1=await this.$refs.list1.getFileFlag()
                          let flag2=await this.$refs.list2.getFileFlag()
                          let arr=[]
                          if(!flag1) arr.push('设备检查')
                          if(!flag2) arr.push('安装条件')
                          if(arr.length>0) {
                            return this.$toast(`请上传${arr.toString()}的必填检查项附件！`)
                          }
                          let isComplete=await this.getFileComplete('EQM_UP_PREPARE_QZJX,EQM_UP_PREPARE_AZTJ',this.models.model.caseId,this.controlData.property.equipmentType)
                          if(!isComplete) return
                          this.showPinion1=true
                        })
                        .catch((err) => {
                            console.log(err);
                            this.$toast('请填写安装条件的必填项！')
                        });
              },
              savePass(){
                this.showPinion1=false
                this.send();
              },
            },
            
        };
    }
}
</script>

<style lang="less" scoped>
@import url('../../../../assets/css/commonPage.less');
.submit-btn {
    flex: 1;
    margin: 0 10px;
    border-radius: 24px;
}
/deep/.van-radio-group{
  display: flex;
  align-items: center;
  .van-radio{
    flex: 1;
    padding: 10px 8px;
    border: 1px solid #D7DCE4;
    border-radius: 20px;
    font-size: 13px;
    &:first-child{
      margin-right: 10px;
    }
    .van-radio__label{
      margin-left: 6px;
    }
  }
}
.df-box{
  display: flex;
  .index{
    flex-shrink: 0;
    width: 25px;
    height: 22px;
    background: rgba(51, 133, 255, 0.1);
    color: #3385FF;
    margin-right: 15px;
    text-align: center;
    line-height: 22px;
    font-size: 12px;
  }
  .right-content-box{
    flex: 1;
    .title{
      font-weight: 400!important;
    }
  }
}
.myForm{
  /deep/ .van-field.van-cell{
    padding: 0;
    .van-field__body{
      background-color: #F5F7FA;
      border: 1px solid #E4E8EB;
      border-radius: 4px;
      padding: 10px 15px;
    }
    &.my-radio{
      .van-field__body{
        background-color: transparent;
        border: none;
        padding: 0;
        .van-radio-group{
          width: 100%;
          .van-radio__label--disabled {
              color: #323233;
          }
        }
      }
    }
  }
}
/deep/ .van-notice-bar__content{
  font-size: 12px;
  font-weight: 400;
}
.common-page {
  /deep/.search-list{
    padding: 5px!important;
  }
}
</style>
